//
//  timeTableView.m
//  ElektroM
//
//  Created by Michael on 12.10.09.
//  Copyright 2009 Artgruppe inc. All rights reserved.
//

#import "timeTableView.h"
#import "railwaysController.h"
#import "dataBase.h"
#import "AtomicElementViewController.h"
#import "Train.h"
#import "Constants.h"
#import "timeTableAnother.h"


@implementation timeTableView
@synthesize _nStationId, _direction;
@synthesize _frmBrother;
@synthesize _sDataBaseName;
@synthesize tableView;
@synthesize strTitle;
@synthesize timeFilter;
@synthesize detailedViewController;
@synthesize toolbar;
@synthesize tabBarController;

-(void)updateData
{
	//printf("timeTableView! I want update my resources!\n");
	// here we would use database for showing up a time table:
	if(_db==nil){
		_db=[dataBase alloc];
		_db.namePrefix=_sDataBaseName;	
		_db.databaseName=[_sDataBaseName stringByAppendingString:@"Railways.sqlite"];	
	}
	
	// get current time:
	NSString *sCurTime;
	if(_bUseFilter)
	{
		NSDate* CurDate=[NSDate date];
		NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc] init] autorelease];
		[timeFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
		[timeFormatter setDateStyle:NSDateFormatterNoStyle];	
		[timeFormatter setTimeStyle:NSDateFormatterMediumStyle];	
		
		sCurTime = [timeFormatter stringFromDate:CurDate];
		//printf("Cur time: %s\n", [sCurTime UTF8String]);
	}
	else
		sCurTime=@"00:00:00";
	
	// read out data from the database:
	[_db initialization];
	
	_aiTimes = [_db readTimeTableAsNSArray: self._nStationId withTime:sCurTime withDirection:_direction];
	_aiStartStations = [_db getStartStationsAsNSArray];
	_aiEndStations = [_db getEndStationsAsNSArray];
	_aiiTrainInfo = [_db getTrainInfoAsNSArray];
	_aiTrainIds = [_db getTrainIdsAsNSArray];
	
	if(_direction)
		[self setTitle:NSLocalizedString(@"ToMoscow", @"Shows time table to Moscow")];	
	else
		[self setTitle:NSLocalizedString(@"FromMoscow", @"Shows time table from Moscow")];	
	
		
	if(![strTitle isEqualToString:@""])
	{
		self.navigationItem.prompt = strTitle;
	}
	
	NSString* strTextOfButton;	
	//insert another button for showing opposing _direction:	
	if(_direction)
		strTextOfButton=NSLocalizedString(@"FromMoscow", @"Shows time table from Moscow");
	else
		strTextOfButton=NSLocalizedString(@"ToMoscow", @"Shows time table to Moscow");			
	
	UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] 
					  initWithTitle:strTextOfButton
					  style:UIBarButtonItemStylePlain 
					  target:self action:@selector(showAnotherDirection)]; 

	self.navigationItem.rightBarButtonItem = anotherButton; 
	
	[anotherButton release];
	[tableView reloadData];	
}

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		_bUseFilter=true;
		//printf("Used filter!\n");		
		_frmBrother=nil;		
    }	
    return self;
}

- (IBAction) filterAddRemove
{
	if(_bUseFilter)
	{
		_bUseFilter=false;
		[timeFilter setTitle:NSLocalizedString(@"TimeFilter-", @"")];
		[self updateData];
	}
	else
	{	
		_bUseFilter=true;
		[timeFilter setTitle:NSLocalizedString(@"TimeFilter+", @"")];
		[self updateData];
	}	
}

- (IBAction) showAnotherDirection
{
	if(_frmBrother==nil)
	{						
		timeTableAnother* controller=[[timeTableAnother alloc] initWithNibName:@"timeTableAnother" 
									bundle:nil];
		self._frmBrother = controller;
		[controller release];		
	}
	
	//_frmBrother._direction = 1 - self._direction;
	_frmBrother.strTitle = strTitle;
	_frmBrother._sDataBaseName=self._sDataBaseName;
	_frmBrother.tabBarController=self.tabBarController;
	[(timeTableAnother*)_frmBrother setTimeInfo:_nStationId withDirection:(1-self._direction)];

	
	[self.navigationController pushViewController:_frmBrother animated:YES];
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[timeFilter setTitle:NSLocalizedString(@"TimeFilter+", @"")];
	[super viewDidLoad]; 
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [_aiTimes count];
}

- (UITableViewCell *)tableView:(UITableView *)tableViewMy cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *kCellIdentifier = @"cellID";
	
	UITableViewCell *cell = [tableViewMy dequeueReusableCellWithIdentifier:kCellIdentifier];
	if (!cell)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCellIdentifier] autorelease];
        
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        cell.textLabel.backgroundColor = [UIColor clearColor];
		cell.textLabel.opaque = NO;
		cell.textLabel.textColor = [UIColor blackColor];
		cell.textLabel.highlightedTextColor = [UIColor whiteColor];
		cell.textLabel.font = [UIFont boldSystemFontOfSize:18];
		
		cell.detailTextLabel.backgroundColor = [UIColor clearColor];
		cell.detailTextLabel.opaque = NO;
		cell.detailTextLabel.textColor = [UIColor grayColor];
		cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor];
		cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    }
    
	// get info about time table here...   
	if(!_bReleaseMySelf){
	//cell.textLabel.text = [_aiTimes objectAtIndex: indexPath.row];	
		cell.textLabel.text = @"12:00";

	int nSched=[[_aiiTrainInfo objectAtIndex: indexPath.row] intValue];
	if(nSched!=0 && nSched!=2 && nSched!=3)
	{
		cell.textLabel.textColor = [UIColor greenColor];		
	}
	else if(nSched==2 || nSched==3)		
	    cell.textLabel.textColor = [UIColor redColor];
	else
	    cell.textLabel.textColor = [UIColor blackColor];

	if(_direction)
		cell.detailTextLabel.text= [_aiEndStations objectAtIndex: indexPath.row];
	else
		cell.detailTextLabel.text= [_aiEndStations objectAtIndex: indexPath.row];
	}
	else
	{
		cell.textLabel.text = @"None";
		cell.detailTextLabel.text = @"??.??";
		
	}	
	
	return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{  	
	Train* iTrain=[Train alloc];
	iTrain.sTime = [_aiTimes objectAtIndex: indexPath.row];
	iTrain.startStation = [_aiStartStations objectAtIndex: indexPath.row];
	iTrain.endStation = [_aiEndStations objectAtIndex: indexPath.row];
	iTrain.trainNumber=[_aiTrainIds objectAtIndex: indexPath.row];
	iTrain.nInfo = [[_aiiTrainInfo objectAtIndex: indexPath.row] intValue];


	if(detailedViewController!=nil)
	{
		[detailedViewController release];
		detailedViewController=nil;
	}
	
	AtomicElementViewController* targetViewController = [AtomicElementViewController alloc];
	[targetViewController init];	
	targetViewController.iTrain=iTrain;
	targetViewController.dataBaseName=_sDataBaseName;	
	[targetViewController loadView];	
	detailedViewController=targetViewController;
		
    [self.navigationController pushViewController:detailedViewController animated:YES];
}


#pragma mark -
#pragma mark BarReleaseStuff
- (void)viewWillAppear:(BOOL)animated{
	//[self updateData];
	_bReleaseMySelf=false;
    // kick him off, that bustard!
	if(!tabBarController.tabBar.hidden)
    {
	tabBarController.tabBar.hidden=YES;
    }	
    // that busturd did disturb our parent elements:
				  // rearrange them:
    tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-84);		

    [toolbar removeFromSuperview];
    toolbar.frame=CGRectMake(0, 436, kScreenWidth, 44);
    [tabBarController.view addSubview:toolbar];
}

- (void)viewWillDisappear:(BOOL)animated{
	//printf("View disappeared!\n");	
	[toolbar removeFromSuperview];
	[self.view addSubview:toolbar];
	_bReleaseMySelf=true;
}

#pragma mark -
#pragma mark Memory Releases
- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];	
	// Release any cached data, images, etc that aren't in use.
}

-(void) releaseUnneededData
{
	//printf("time table... I want dissolve myself\n");
	if(_db!=nil){
		_db.namePrefix=nil;
		_db.databaseName=nil;
	    [_db releaseAllElementsOfTimeTableAsNSArray];
	    [_db release];	 
	    _db=nil;
	}
	
	if(_frmBrother!=nil){
		[_frmBrother releaseUnneededData];
	}
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;	
    if(tableView!=nil)
	[tableView release];
    tableView = nil;
    if(_frmBrother!=nil)
	[_frmBrother release];
    _frmBrother = nil;
    if(_sDataBaseName!=nil)
	[_sDataBaseName release];
    _sDataBaseName = nil;
    if(strTitle!=nil)
	[strTitle release];
    strTitle = nil;	
    if(detailedViewController!=nil)
	[detailedViewController release];
    detailedViewController=nil;
}

- (void)dealloc {	
    [super dealloc];
}


@end
